<template>
  <div class="tit01">数字化转型</div>
  <div class="">
    <div style="width: 100%; height: 350px" ref="channelChart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useIndicatorAPI } from '../composables/useIndicatorAPI.js'
import API_CONFIG from '../config/api.js'

const channelChart = ref(null)
let channelChartInstance = null
const { getIndicatorData } = useIndicatorAPI()

// 定义各个渠道的指标名称和显示名称
const channelIndicators = [
  { name: '传统设备月交易量', displayName: '传统设备' },
  { name: '企业手机银行月交易笔数', displayName: '企业手机银行' },
  { name: '个人网上银行月交易笔数', displayName: '个人网上银行' },
  { name: '企业网上银行月交易笔数', displayName: '企业网上银行' },
  { name: '个人手机银行月交易笔数', displayName: '个人手机银行' },
  { name: '线下渠道月交易量', displayName: '线下渠道' },
  { name: '智能设备月交易量', displayName: '智能设备' },
  { name: '柜面渠道月交易量', displayName: '柜面渠道' }
]

// 获取渠道数据
const loadChannelData = async () => {
  try {
    const promises = channelIndicators.map(indicator => getIndicatorData(indicator.name))
    const results = await Promise.allSettled(promises)
    
    const channelData = []
    let totalCount = 0
    
    console.log('开始处理渠道数据...')
    
    // 处理每个渠道的数据
    for (let i = 0; i < results.length; i++) {
      const result = results[i]
      const indicator = channelIndicators[i]
      
      console.log(`处理渠道 ${indicator.name}:`, result)
      
      if (result.status === 'fulfilled' && result.value) {
        console.log(`${indicator.name} API响应:`, result.value)
        
        if (result.value.datas && result.value.datas.length > 0) {
          // 获取最新一期的数据（第一条记录，因为按日期倒序）
          const latestData = result.value.datas[0]
          console.log(`${indicator.name} 最新数据:`, latestData)
          
          // 使用配置文件中的数据格式设置
          const dbConfig = API_CONFIG.getDatabaseConfig()
          const dataFormat = dbConfig.DATA_FORMAT
          
          // 根据配置获取指标值
          const count = parseFloat(latestData[dataFormat.VALUE_INDEX] || 0)
          
          console.log(`${indicator.name} 数据格式类型:`, dataFormat.TYPE)
          console.log(`${indicator.name} 原始数据:`, latestData)
          console.log(`${indicator.name} 指标值索引:`, dataFormat.VALUE_INDEX)
          console.log(`${indicator.name} 解析数量:`, count)
          
          channelData.push({
            name: indicator.displayName,
            value: count,
            originalName: indicator.name
          })
          totalCount += count
        } else {
          console.log(`${indicator.name} 没有数据，设置为0`)
          channelData.push({
            name: indicator.displayName,
            value: 0,
            originalName: indicator.name
          })
        }
      } else {
        console.error(`${indicator.name} API调用失败:`, result.reason)
        // 如果没有数据，设置为0
        channelData.push({
          name: indicator.displayName,
          value: 0,
          originalName: indicator.name
        })
      }
    }
    
    console.log('所有渠道数据:', channelData)
    console.log('总交易数量:', totalCount)
    
    // 计算占比并更新图表
    const chartData = channelData.map(item => ({
      name: item.name,
      value: totalCount > 0 ? ((item.value / totalCount) * 100).toFixed(2) : 0,
      actualValue: item.value,
      originalName: item.originalName
    }))
    
    console.log('图表数据:', chartData)
    updateChart(chartData)
    
  } catch (error) {
    console.error('加载渠道数据失败:', error)
    // 显示模拟数据用于测试
    const defaultData = channelIndicators.map((indicator, index) => ({
      name: indicator.displayName,
      value: (Math.random() * 20 + 5).toFixed(2),
      actualValue: Math.random() * 1000000 + 100000,
      originalName: indicator.name
    }))
    console.log('使用模拟数据:', defaultData)
    updateChart(defaultData)
  }
}

// 更新图表
const updateChart = (data) => {
  if (!channelChartInstance) return
  
  const option = {
    color: ['#29D9D5', '#3C8BFF', '#4A5DDE', '#5A3EC8', '#FF6B9D', '#FF8C42', '#6BCF7F', '#FFD93D'],
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const actualValue = params.data.actualValue
        const originalName = params.data.originalName || params.name
        
        // 根据指标名称判断单位
        let unit = '笔'
        let formattedValue = actualValue.toLocaleString()
        
        if (originalName.includes('交易量')) {
          unit = '笔'
          if (actualValue >= 10000) {
            formattedValue = (actualValue / 10000).toFixed(2) + '万笔'
          } else {
            formattedValue = actualValue.toLocaleString() + '笔'
          }
        } else if (originalName.includes('交易笔数')) {
          unit = '笔'
          if (actualValue >= 10000) {
            formattedValue = (actualValue / 10000).toFixed(2) + '万笔'
          } else {
            formattedValue = actualValue.toLocaleString() + '笔'
          }
        }
        
        return `${params.name}<br/>指标: ${originalName}<br/>交易数量: ${formattedValue}<br/>占比: ${params.value}%`
      },
      backgroundColor: 'rgba(0,0,0,0.7)',
      textStyle: {
        color: '#fff'
      }
    },
    legend: {
      show: false
    },
    series: [{
      type: 'pie',
      radius: ['30%', '60%'],
      center: ['50%', '40%'],
      data: data,
      label: {
        show: true,
        color: '#fff',
        fontSize: 9,
        formatter: (params) => {
          return `${params.name}\n${params.value}%`
        }
      },
      labelLine: {
        show: true,
        lineStyle: {
          color: '#fff'
        }
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  channelChartInstance.setOption(option)
}


// 初始化图表
const initChart = () => {
  if (channelChart.value) {
    channelChartInstance = echarts.init(channelChart.value)
    loadChannelData()
  }
}

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  if (channelChartInstance) {
    channelChartInstance.dispose()
  }
})
</script>
